#include <stdio.h>
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>

int get_gpio_num(int group, int pin)
{
	return 496 - group * 16 + pin;
}

int check_gpio_dir(int num)
{
	char filepath[256] = { '\0' };
	
	// Get full directory name
	snprintf(filepath, 256, "/sys/class/gpio/gpio%d", num);

	return access(filepath, F_OK);
}

int set_gpio_attr(int num, const char *attr, const char *value)
{
	char filepath[256] = { '\0' };
	int fd;

	// Get full directory name
	snprintf(filepath, 256, "/sys/class/gpio/gpio%d/%s", num, attr);

	printf("Write \"%s\" into %s\n", value, filepath);
	fd = open(filepath, O_WRONLY);
	write(fd, value, strlen(value));

	close(fd);
}

int main(int argc, char *argv[])
{
	int i, fnum;
	char gpio_num[10] = { '\0' };

	int export_fd;

	// 0 - DEV0 On
	// 1 - DEV0 Off
	// 2 - DEV1 On
	// 3 - DEV1 Off
	// 4 - DEV2 On
	// 5 - DEV2 Off
	
	if (argc > 2) {
		
		if (strcmp(argv[1], "red") == 0) {
			fnum = get_gpio_num(0, 13);
		} else if (strcmp(argv[1], "green") == 0) {
			fnum = get_gpio_num(1, 1);
		} else if (strcmp(argv[1], "blue") == 0) {
			fnum = get_gpio_num(5, 0);
		} else {
			printf("Invalid color: %s\n", argv[1]);
			return 0;
		}

		if (check_gpio_dir(fnum)) {
			export_fd = open("/sys/class/gpio/export", O_WRONLY);
			snprintf(gpio_num, 10, "%d", fnum);
			write(export_fd, gpio_num, strlen(gpio_num));
		}

		set_gpio_attr(fnum, "direction", "out");
		set_gpio_attr(fnum, "active_low", "0");

		if (strcmp(argv[2], "on") == 0) {
			set_gpio_attr(fnum, "value", "1");
		} else if (strcmp(argv[2], "off") == 0) {
			set_gpio_attr(fnum, "value", "0");
		} else {
			printf("Invalid action: %s\n", argv[2]);
			return 0;
		}
	} else {
		printf("Usage: led <color> <on/off>\n");
	}

	return 0;
}

